﻿namespace PreGUI.Helpers
{
    using PreGUI.Interfaces;
    using PreGUI.Widgets;
    using System.IO;
    using System.Linq;
    using System.Xml;

    /// <summary>
    /// Utility class to load PreGui controls from Xml.
    /// </summary>
    public static class PGXmlLoader
    {
        public static PGWindow LoadFromXml(string xmlString)
        {
            using (var xmlReader = XmlReader.Create(new StringReader(xmlString)))
            {
                var doc = new XmlDocument();
                return PGWindow.LoadFromXml(doc.ReadNode(xmlReader));
            }
        }

        public static IPGControl XmlProcessChildControl(this XmlNode node)
        {
            var type = System.Type.GetType("PreGUI.Widgets.PG" + node.Name);

            if (type == null)
                return null;

            var iType = type.GetInterface("IPGControl");

            if (iType == null)
                return null;

            return ((IPGControl)System.Activator.CreateInstance(type)).GenerateFromXmlNode(node);
        }

        public static IPGControl[] XmlProcessChildControls(this XmlNode[] nodes)
        {
            return nodes.Select(x => x.XmlProcessChildControl()).ToArray();
        }
    }
}